<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace App\User;

use Core\Db\Db as Db;

/**
 * PSE前台首页
 * @author LazyPHP
 * @version 1.0
 */
class Login extends Common {

    /**
     * 初始化登陆页面
     */
    public function index() {
        $this->display();
    }

    /**
     * 执行登录
     */
    public function doLogin() {
        $this->checkVerify('verify');
        $data['account'] = $this->is_p('account', '请填写登陆账号');
        $data['password'] = md5(md5($this->is_p('password', '请填写登陆账号')));
        $db = $this->db('user');
        $existUser = $db->where('account = :account and password = :password')->find($data);
        $this->determineSqlExecResult($existUser, '用户不存在或者被禁用');
        $db->where('uid = :uid')->save(array('last_login' => time(), 'uid' => $existUser['uid']));
        $_SESSION['user'] = $existUser;
        $this->recordLoginStatus();
        $this->success('登陆成功!', $this->url('User-Index-index'));
    }

    /**
     * 记录登录状态
     */
    private function recordLoginStatus() {
        $record = $this->p('record');
        if ($record == 'true') {
            $db = $this->db('cookie');
            $data['cookie'] = uniqid(md5(time()));
            $data['uid'] = $_SESSION['user']['uid'];
            $data['createtime'] = time();
            $addCookie = $db->add($data);
            if (empty($addCookie)) {
                echo '警告:系统自动记录功能无法正常运行!';
            }
            setcookie('recordLogin', $data['cookie'], time() + 864000);
        }
    }

    /**
     * 执行账号退出
     */
    public function logout() {
        unset($_SESSION['user']);
        setcookie("recordLogin", "", time() - 3600);
        $this->success('账号已经退出了登陆!', $this->url('User-Login-index'));
    }

}